<!DOCTYPE html>
<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="description" content="">
    <meta name="author" content="">
    <title>Websocket模拟测试</title>
    <script type="text/javascript" src="http://jic.betools.vip/common/web/js/jquery.min.js"></script>
    <script type="text/javascript" src="http://jic.betools.vip/tools/js/json.js"></script>
</head>
<body>
    <input type="text" style="width:200px;" id="wsDomain" value="ws://wsmocktest.betools.vip:9501" />
    <button id="connect">连接</button>
    <button id="close">断开</button>
    <br>
    <textarea rows="20" cols="80" id="content"></textarea>
    <button id="send">发送</button>
    <br>
    <textarea rows="20" cols="80" id="messageDiv"></textarea>
    <script>
        var ws = null;
        $("#connect").click(function(){
            var domain = $("#wsDomain").val();
            if(domain == '' || domain == 'undefine') {
                alert('域名不能为空');
                return false;
            }
            ws = socketInit(domain, "messageDiv");
        });
        
        $("#send").click(function(){
            var content = $("#content").val();
            console.log(content);
            sendMsg(ws, "text", content);
        });

        function sendMsg(ws, type, content) {
            if(!ws) {
                alert("请先连接后，再发送");
                return false;
            }
            if(!type || !content) {
                alert("参数错误");
                return false;
            }
            //发送文本
            var oldcontent = $("#messageDiv").val();
            var newcontent = oldcontent + "\n【客户端发送】：" + content + "\n";
            console.log(newcontent);
            $("#messageDiv").val(newcontent);
            
            var msg = {"type":type, "msg":content};
            ws.send(JSON.stringify(msg));
        }

        
        function socketInit(domain, contentId) {
            if(!domain || !contentId) {
                alert("参数错误");
                return false;
            }
            
            var ws = new WebSocket(domain);
            //readyState属性返回实例对象的当前状态，共有四种。
            //CONNECTING：值为0，表示正在连接。
            //OPEN：值为1，表示连接成功，可以通信了。
            //CLOSING：值为2，表示连接正在关闭。
            //CLOSED：值为3，表示连接已经关闭，或者打开连接失败
            //例如：if (ws.readyState == WebSocket.CONNECTING) { }
             
            //【用于指定连接成功后的回调函数】
            ws.onopen = function (evt) {
                console.log("Connection open ...");
            };
            //ws.addEventListener('open', function (event) {
    //            ws.send('Hello Server!');
            //};
             
            //【用于指定收到服务器数据后的回调函数】
            //【服务器数据有可能是文本，也有可能是二进制数据，需要判断】
            ws.onmessage = function (event) {
                if (typeof event.data === String) {
                    console.log("Received data string");
                }
         
                if (event.data instanceof ArrayBuffer) {
                    var buffer = event.data;
                    console.log("Received arraybuffer");
                }
                console.log("Received Message: " + event.data);
                var jsonData = event.data;
                var arrData = JSON.parse(jsonData);
                if (arrData.type != 'ping') {
                    var oldcontent = $("#"+contentId).val();
                    var newcontent = oldcontent + "\n【服务端返回】：" + arrData.msg + "\n";
                    $("#"+contentId).val(newcontent);
                }
                //ws.close();
            };
             
            //[【于指定连接关闭后的回调函数。】
            ws.onclose = function (evt) {
                console.log("Connection closed.");
            };
             
            ws.onerror = function (event) {
            };
             
            ws.addEventListener("error", function (event) {
            });

            return ws;
        }

    </script>
</body>
</html>
